import {
	defineStore
} from 'pinia'
import {
	loginApi
} from '@/common/api/login/index.js'
import {
	handleTree
} from '@/common/common.js'

export const useUserStore = defineStore('userStore', {
	state: () => {
		return {
			userType: '',
			userInfo: "",
			token: '',
			menus: [],
			storeInfo: '',
		}
	},
	actions: {
		async getUserLoginInfo() {
			try {
				//获取登录用户信息
				const res = await loginApi.getLoginInfo()
				console.log('res111==>', res);
				if (res.code != 200) return
				//更新用户信息到pinia
				this.setUserLoginInfo(res.data)
				this.setMenus()

				return this.userInfo
			} catch (e) {
				console.error(e);
			} finally {}
		},
		//设置登录信息
		setUserLoginInfo(data) {
			this.userType = data.oUserType
			this.userInfo = data
		},
		//设置门店信息
		setStoreInfo(data) {
			this.storeInfo = data
		},
		setUserType(type) {
			this.userType = type
		},
		setToken(token) {
			this.token = token
		},
		getMenus() {
			return this.menus
		},
		setMenus() {
			let menu = handleTree(this.userInfo.menus.filter((item) => {
					return item.path && item.sourceType == 2 && item.visibleFlag
				}).sort((a, b) => a.num - b.num), 'id',
				'fMenuId')
			this.menus = menu
			console.log('菜单==>', menu);
		},
		async removeData() {
			try {
				const res = await loginApi.logout()
				console.log('退出登录==>', res)

				this.userInfo = ""
				this.storeInfo = ""
				this.token = ''
				this.menus = []
			} catch (e) {
				console.error(e);
			} finally {}
		}
	},
	unistorage: {
		key: "user", // 缓存的键，默认为该 store 的 id，这里是 common,
		paths: ['token', 'userType', 'menus', 'userInfo', 'storeInfo'], // 需要缓存的路径
	},
})